package com.zhizihua.content.service.impl;

import com.zhizihua.content.mapper.CourseCategoryMapper;
import com.zhizihua.content.model.dto.CourseCategoryTreeDto;
import com.zhizihua.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 课程分类接口实现类
 * @author: zhizihua
 * @Email: 2876290193@qq.com
 * @date: 2025/5/11
 */

@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        // 调用mapper递归查询出分类信息
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);

        // 找到每一个节点的子节点，最终封装成List<CourseCategoryTreeDto>
        // 先将list转为map，key为id，value为CourseCategoryTreeDto对象。
        //        filter(item->!id.equals(item.getId())) 过滤掉根节点
        //        collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2))
        //        转为map，并且当key1和key2重复时，使用key2覆盖key1
        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        // 定义一个list，为最终的list
        List<CourseCategoryTreeDto> courseCategoryList = new ArrayList<>();
        // 从头遍历 List<CourseCategoryTreeDto>,一边遍历一边找子节点，并放在父节点的childrenTreeNodes
        courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).forEach(item -> {
            // 当父节点id等于根节点id时，放入list中（一级目录，除去根节点）
            if (item.getParentid().equals(id)){
                courseCategoryList.add(item);
            }
            // 找到节点的父节点
            CourseCategoryTreeDto courseCategoryParent = mapTemp.get(item.getParentid());
            if (courseCategoryParent != null){
                if (courseCategoryParent.getChildrenTreeNodes() == null){
                    // 如果该父节点的childrenTreeNodes为空，则创建一个空的list
                    courseCategoryParent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                // 将该节点放在父节点的childrenTreeNodes属性中
                courseCategoryParent.getChildrenTreeNodes().add(item);
            }
        });

        return courseCategoryList;
    }
}
